# 全局配置参数
import os
from pathlib import Path

# 获取项目根目录的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 在生产环境中使用正确的绝对路径
PROJECT_ROOT = "/projects/volcano-domain-site-workbox"
if not os.path.exists(PROJECT_ROOT):
    PROJECT_ROOT = BASE_DIR

BASE_URL = "https://work8.top"  # 网站域名
UPLOAD_DIR = os.path.join(PROJECT_ROOT, "static/uploads")   # 上传目录

# 文件上传配置
MAX_SIZE_MB = 100
ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"]

# 确保上传目录存在
Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)

# PDF处理和OCR相关配置
# =====================

# 系统内存检测（简单方法）
def get_system_memory():
    """获取系统可用内存（MB）"""
    try:
        with open('/proc/meminfo', 'r') as f:
            meminfo = f.read()
            available = None
            for line in meminfo.splitlines():
                if 'MemAvailable:' in line:
                    available = int(line.split()[1]) // 1024  # 转换为MB
                    break
            if available:
                return available
            else:
                # 如果找不到MemAvailable，返回一个保守的默认值
                return 512
    except:
        # 出错时返回一个保守的默认值
        return 512

AVAILABLE_MEM_MB = get_system_memory()

# 内存优化配置 - 根据系统可用内存自动调整
if AVAILABLE_MEM_MB < 300:
    # 极低内存模式
    PDF_BATCH_SIZE = 1  # 一次只处理一页
    PDF_CONCURRENT_TASKS = False  # 禁用并发处理
    OCR_USE_ANGLE_CLS = False  # 禁用角度分类器以节省内存
elif AVAILABLE_MEM_MB < 600:
    # 低内存模式
    PDF_BATCH_SIZE = 2  # 批处理2页
    PDF_CONCURRENT_TASKS = False
    OCR_USE_ANGLE_CLS = True
else:
    # 标准内存模式
    PDF_BATCH_SIZE = 3  # 批处理3页
    PDF_CONCURRENT_TASKS = False
    OCR_USE_ANGLE_CLS = True

# 临时文件目录 - 优先使用内存文件系统，但如果内存太少则使用磁盘
if AVAILABLE_MEM_MB > 400 and os.path.exists('/dev/shm'):
    PDF_TEMP_DIR = '/dev/shm/pdf_temp'
else:
    PDF_TEMP_DIR = os.path.join(PROJECT_ROOT, 'output_files/temp')

# 确保PDF临时目录存在
try:
    Path(PDF_TEMP_DIR).mkdir(parents=True, exist_ok=True)
except:
    # 如果/dev/shm不可写，则使用默认目录
    PDF_TEMP_DIR = os.path.join(PROJECT_ROOT, 'output_files/temp')
    Path(PDF_TEMP_DIR).mkdir(parents=True, exist_ok=True)

# OCR模型配置
OCR_USE_GPU = False  # 是否使用GPU加速OCR
OCR_LANG = "ch"  # 默认OCR语言

# 水印去除配置
DEFAULT_WATERMARK_REMOVAL = 'color_filter'  # 默认水印去除方法 

# 最大内存限制配置（使用Limit内存的百分比，避免内存溢出）
MAX_MEMORY_PCT = 70  # 使用系统最大内存的百分比 

# 内存监控和诊断函数
def get_memory_info():
    """
    获取系统内存使用的详细信息
    
    返回:
        dict: 包含内存使用信息的字典
    """
    info = {}
    
    try:
        # 获取系统内存信息
        with open('/proc/meminfo', 'r') as f:
            meminfo = f.read()
            
            # 提取关键内存指标
            for line in meminfo.splitlines():
                if 'MemTotal:' in line:
                    info['total_kb'] = int(line.split()[1])
                    info['total_mb'] = info['total_kb'] // 1024
                elif 'MemFree:' in line:
                    info['free_kb'] = int(line.split()[1])
                    info['free_mb'] = info['free_kb'] // 1024
                elif 'MemAvailable:' in line:
                    info['available_kb'] = int(line.split()[1])
                    info['available_mb'] = info['available_kb'] // 1024
                elif 'SwapTotal:' in line:
                    info['swap_total_kb'] = int(line.split()[1])
                    info['swap_total_mb'] = info['swap_total_kb'] // 1024
                elif 'SwapFree:' in line:
                    info['swap_free_kb'] = int(line.split()[1])
                    info['swap_free_mb'] = info['swap_free_kb'] // 1024
        
        # 计算使用百分比
        info['used_mb'] = info['total_mb'] - info['free_mb']
        info['used_percent'] = (info['used_mb'] / info['total_mb']) * 100
        
        # 计算可用百分比
        info['available_percent'] = (info['available_mb'] / info['total_mb']) * 100
        
        # 如果有swap，计算swap使用情况
        if 'swap_total_mb' in info and info['swap_total_mb'] > 0:
            info['swap_used_mb'] = info['swap_total_mb'] - info['swap_free_mb']
            info['swap_used_percent'] = (info['swap_used_mb'] / info['swap_total_mb']) * 100
        
        # 内存状态评估
        if info['available_percent'] < 10:
            info['status'] = 'critical'
        elif info['available_percent'] < 20:
            info['status'] = 'warning'
        else:
            info['status'] = 'ok'
    except Exception as e:
        info['error'] = str(e)
    
    return info

# 添加一个API路由来获取内存状态
def add_memory_route(app):
    """为应用添加内存状态API路由"""
    from fastapi import FastAPI
    
    if not isinstance(app, FastAPI):
        return
    
    @app.get("/system/memory")
    def get_memory_status():
        """获取当前系统内存状态"""
        memory_info = get_memory_info()
        
        # 添加建议
        if memory_info.get('status') == 'critical':
            memory_info['suggestion'] = "系统内存严重不足，建议减小批处理大小或添加swap空间"
        elif memory_info.get('status') == 'warning':
            memory_info['suggestion'] = "系统内存较低，建议避免处理大型文件"
            
        # 添加PDF处理相关配置
        memory_info['pdf_batch_size'] = PDF_BATCH_SIZE
        memory_info['pdf_concurrent_tasks'] = PDF_CONCURRENT_TASKS
        memory_info['ocr_use_angle_cls'] = OCR_USE_ANGLE_CLS
            
        return memory_info 